define(function(require, exports, module){
//	require("resource/js/easyui/themes/icon.css");
	require("resource/js/easyui/easyloader.js");
	require("resource/js/component/rules.js");
	require("resource/js/component/jqxcore.js");
	require("resource/js/component/jqxdraw.js");
	require("dcs/section/css/questions.css");
	var AJAX = require("resource/js/component/ajax.js");
	var CONST = require("resource/js/config/const.js");
	var E = require("resource/js/component/easyutil.js");
	var sectionId = sessionStorage.getItem('sectionId');
	$('.darwList').jqxDraw();
	var renderer = $('.darwList').jqxDraw('getInstance');
    var size = renderer.getSize();
	var metre = 10;  //1px = 1m
	var firstPileKey = {};
	var dgutil = undefined;
	var config = {
		name:"拌合站信息",
		column:[[
			{field:'sectionId',title:'标段ID',width:100,align:'center',height:50,hidden:true},
			{field:'mixingName',title:'拌合站',width:100,align:'center',height:50,hidden:false},
			{field:'productionSchedule',title:'生产进度',width:100,align:'center',height:50,hidden:false,
				formatter: function (value, row) {
					var val = Number(row.sumAlreadyTotal) / Number(Number(row.sumPlannedTotal)*1000) ;
					if(isNaN(parseInt(val))){
						val = 0;
					}else{
						val = Number(val * 100).toFixed(2);
					}
					return val+"%";
				}
			},
			{field:'batch',title:'今日出料',width:100,align:'center',height:50,hidden:false,
				formatter: function (value, row) {
					var valBatch = row.batch == undefined ? 0 : row.batch + "批，";
					var valDataTotal =  row.dataTotal == undefined ? 0 : row.dataTotal + "kg";
					return valBatch + valDataTotal;
				}
			},
			{field:'sumPlannedTotal',title:'计划生产',width:100,align:'center',height:50,hidden:false,
				formatter: function (value, row) {
                    var val = row.sumPlannedTotal;
                    if(isNaN(parseInt(val)) || val == undefined){
                        val = 0 + "吨";
                    }else{
                        if((Number(val)/10000) < 1){
                            val = Number(val).toFixed(2) + "吨";
                        }else{
                            val = Number(Number(val)/10000).toFixed(2) + "万吨";
                        }
                    }
					return val;
				}
			},
			{field:'sumAlreadyTotal',title:'已生产',width:100,align:'center',height:50,hidden:false,
				formatter: function (value, row) {
                    var val = row.sumAlreadyTotal;
			        if(isNaN(parseInt(val)) || val == undefined){
			            val = 0 +"吨";
                    }else{
                        val = Number(Number(row.sumAlreadyTotal)/1000).toFixed(2) + "吨";
                    }
					return val;
				}
			},
			{field:'pendingProduction',title:'待生产',width:100,align:'center',height:50,hidden:false,
				formatter: function (value, row) {
					var val = Number(Number(row.sumPlannedTotal) - Number(Number(row.sumAlreadyTotal)/1000)).toFixed(2);
					if(isNaN(parseInt(val))){
						val = 0 ;
					}
					return val +"吨";
				}
			},
			{field:'time',title:'最后生产时间',width:100,align:'center',height:50,hidden:false,
                formatter: function (value, row) {
                    if(row.time != null && "" != row.time && row.time != undefined ){
                        return  row.time.toString().split('.')[0];
                    }
                    return  row.time;
                }
            },

		]]
	}
	var initpage = function(){
			dgutil = E.ajaxDataGrid(datagridconfig);
	}

	function proportionBar(producedTotal,plannedTotal){

		var BaseiD = echarts.init(document.getElementById("proportionBar"));
		//$("#proportionBar").height("100px");
		option = {
			 grid: [{//外框
		            left: '50',
		            right: '120',
		            containLabel: false,
		        }],
			xAxis: {
				show: false
			},
			yAxis: [{
				show: true,
				data: [],
				inverse: true,
				axisLine: {
					show: false
				},
				splitLine: {
					show: false
				},
				axisTick: {
					show: false
				},
				axisLabel: {
					color: '#fff',
					formatter: function(value, index) {
						// return [
						// 	// '{lg|' + (index + 1) + '}' + '{title|' + value + '} '
						// ].join('\n')
					},
					rich: {
						lg: {
							backgroundColor: '#339911',
							color: '#fff',
							borderRadius: 15,
							 padding: 5,
							align: 'left',
							width: 15,
							height: 15
						},
					}
				},
			}, {
				show: true,
				inverse: true,
				data: [100],
				axisLabel: {
					textStyle: {
						fontSize: 12,
						color: '#fff',
					},
				},
				axisLine: {
					show: false
				},
				splitLine: {
					show: false
				},
				axisTick: {
					show: false
				},
			}],
			series: [{
				name: '框',
				silent: true,
				type: 'bar',
				yAxisIndex: 1,
				data: [100],
				barWidth: 40,
				itemStyle: {
					normal: {
						color: '#f5f6f6',
						borderColor: '#f5f6f6',
						borderWidth: 0.5,
					}
				},

				label: {
					normal: {
						show: true,
						position: 'right',
						color: '#3BCFFF',
						fontSize: 14,
						// formatter:
						// 	function(param) {
						// 		// return '50%';
						// 	},
					}
				},
			},{
				name: '条',
				type: 'bar',
				silent: true,
				yAxisIndex: 0,
				data: [Number((producedTotal / (plannedTotal*1000))*100).toFixed(2)],
				barWidth: 40,
				itemStyle: {
					normal: {
						color: '#3BCFFF',
					}
				},
				label: {
					normal: {
						show: true,
						position: 'inside',
						formatter: '{c}%'
					}
				},
			}]
		};
	/*	BaseiD.on('mouseout', function (params) {
           console.log("移除事件" + params.name)
		})
		BaseiD.on('mouseover', function (params) {
			console.log("移入事件"+ params.name)
		})*/
		BaseiD.setOption(option);
		window.addEventListener("resize", function () {
			BaseiD.resize();
	    });
	}
	var processType="02";
	function proportion(processType){
		var sectionId = sessionStorage.getItem('sectionId');
		AJAX.init().success(function(code,msg,data){
			if(code==0){
				if(data){
					var totalProgress = (data.producedTotal/(data.plannedTotal*1000)) * 100;
					if(isNaN(parseInt(totalProgress))){
						totalProgress = 0;
					}
					$("#progress").text(totalProgress.toFixed(2)+"%");
					proportionBar(data.producedTotal,data.plannedTotal);
				}
			}
		}).error(function(code,msg,data){
			//$.messager.show(msg);
		}).post(BASEPATH+"/dcs/tendersOverviewAction/getTendersProgress.htm",{sectionId:sectionId,processType:processType});
	}

	
	function resizeChartContainer() {
		console.log($('#mainBar').height());
		var outHeight =$('#mainBar').height()-10;
		var dom = document.getElementById('mainBar');
		dom.style.height = outHeight+'px';
	};

	var parem = {
		processType:"02",
		sectionId:sectionId
	}
		
	function Rad(d){
       return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
    }
    //计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
    function GetDistance(lat1,lng1,lat2,lng2){  //#lat为纬度, lng为经度, 一定不要弄错
 
        var radLat1 = Rad(lat1);
        var radLat2 = Rad(lat2);
        var a = radLat1 - radLat2;
        var  b = Rad(lng1) - Rad(lng2);
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
        Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        s = s *6378.137 ;// EARTH_RADIUS;
        s = Math.round(s * 10000) / 10; //输出为米
        return s;
    }
	
    //获取路桩
    var xWidth = 0;
	var getRoadPileKey = function(){
		AJAX.init().success(function(code,msg,data){
		   if(code==0){
			   firstPileKey =data[0];
			   var first = data[0];
			   var x = 10;
			   var y = basicLevelHeight;
			   for(var i=0; i<data.length;i++){
				   var x1 = GetDistance(first.lat,first.lng,data[i].lat,data[i].lng);
				   if(x1!=0){
					   x1 = x + (x1 * metre);
					   renderer.line(x+1, 281, x+1, 285, { stroke: '#c3c3c3', 'stroke-width': 1 });
					   renderer.line(x, y, x1, y, { stroke: '#c3c3c3', 'stroke-width': 1 });
					   x = x1;
					   if(i==data.length-1){
						   xWidth = x;
						   $(".darwList svg").css("width",x+50);
					   }
					   first = data[i];
					   $("<div class='yLineList' style='left:"+x1+"'></div>").appendTo($(".darwList"));
				   }
				   $("<div class='pileKeyList' style='left:"+x+"'>"+data[i].pileKey+"</div>").appendTo($(".darwList"));
			   }
			   renderer.line(x1-1, 281, x1-1, 285, { stroke: '#c3c3c3', 'stroke-width': 1 });
			   var pileKeyList =  $(".pileKeyList");
			   pileKeyList.each(function(i){
				   if(i!=0){
					   $(this).css("margin-left",-$(this).width()/2);
				   }
			   });
			   SectionStatistics(parem);
		   }
		}).post(BASEPATH + '/dcs/intface/queryPileKey.htm', {sectionId:sectionId});
	}
			
	//获取层级	
	var basicLevelHeight = 280;
	var color = ["#35feeb","#15d6ff"];
	function SectionStatistics(parem){
		parem;
		AJAX.init().success(function(code,msg,data){
			if(code==0){
				if(data){
					var xLevel = 5;
					var yLevel = 11;
					var ypoint = 1;
					var y = 0;
					var x = 11;
					var distance = basicLevelHeight / data.length;
					var y1 = distance;
					var top  = y1 / 2; 
					for(var i=0;i<data.length;i++){
						renderer.line(xLevel, ypoint, yLevel, ypoint, { stroke: '#c3c3c3', 'stroke-width': 1 });
						renderer.line(x, y, x, y1, { stroke: '#c3c3c3', 'stroke-width': 1});
						$("<div id="+data[i].layer_id+i+" rad="+distance * (i)+" style='position: absolute; top:"+top+";right:10px'>"+data[i].layer_name+"</div>").appendTo($(".laeryDiv"));
						y = y1;
						top = y1 + distance / 2;
						ypoint = y1+1;
						y1 = y1 + distance;
						$("<div class='lineDiv' style='width:"+xWidth+";height:"+distance+"'></div>").appendTo($(".darwList"));
					}
					renderer.line(xLevel, basicLevelHeight, yLevel, basicLevelHeight, { stroke: '#c3c3c3', 'stroke-width': 1 });
					getqueryLayer(data,2,parem.processType); //最近一个月
				}
			}
		}).error(function(code,msg,data){
			//$.messager.show(msg);
		}).post(BASEPATH+"/dcs/statistics/queryLayer.htm",parem);
	}
	
	var flag = true;

	//获取数据
	var getqueryLayer = function(list,paramKey,processType){
		var option = {
				sectionId:sectionId,
				processType:processType,
				paramKey:paramKey,
		}; 
		AJAX.init().success(function(code,msg,data){
			if(code==0){
				for(var k=0;k<list.length;k++){
					var $temp = data[list[k].layer_name];
					if($temp){
						var distance = GetDistance(firstPileKey.lat,firstPileKey.lng,$temp.latStart,$temp.lngStart);
						var width = GetDistance($temp.latStart,$temp.lngStart,$temp.latEnd,$temp.lngEnd);
						var x = distance * metre + 11;
						width = width * metre;
						var y = Number($("#"+list[k].layer_id +k).attr("rad"));
						var height = basicLevelHeight / list.length;
						if(paramKey==1){
							var colorBg = color[0];
							var res = 1;
						}else{
							var colorBg = color[1];
							var res = 2;
						}
						renderer.rect(x, y, width, height, { stroke: colorBg , fill: colorBg, res:res});
					}
				}
				if(flag){
					getqueryLayer(list,1,parem.processType); //最近三天
					$(".drawloading").hide();
					flag = false;
				}
				$(".darwTab li").unbind("click");
				$(".darwTab li").on("click",function(){
					var svgLine = $(".darwList svg rect");
					var res = $(this).attr("res");
					if($(this).hasClass("current")){
						$(this).removeClass("current");
						svgLine.each(function(){
							if($(this).attr("res")==res){
								$(this).hide();
							}
						});
					}else{
						$(this).addClass("current");
						svgLine.each(function(){
							if($(this).attr("res")==res){
								$(this).show();
							}
						});
					}
				});
				
			}
		}).error(function(code,msg,data){
			//$.messager.show(msg);
		}).post(BASEPATH+"/dcs/statistics/querySectionStatistics.htm?",option);
	}
	
	module.exports = {
		trans:function(id){
			//拌合站信息
			datagridconfig = {
				fitColumns:true,
				singleSelect:false,
				striped:true,
				autoRowHeight:false,
				fit: true,
				columns:config.column,
				eid:"dg",
				url:BASEPATH+'/dcs/tendersOverviewAction/getMixingStationDataStatistics.htm',
				args:parem
			};
			using(["parser","dialog","datagrid" ,"combo","combobox"],function(){
				$(".drawloading").show();
				proportion("02");
				proportionBar("70","380");
				parem.processType='02';
				initpage();
				$(".tab_title").find("span").unbind("click");
				$(".tab_title").find("span").click(function(){
					$(".darwList svg line ,.darwList svg rect").remove();
					$(".laeryDiv div ,.yLineList , .lineDiv , .pileKeyList").remove();
					$(".darwTab li").addClass("current");
					$(this).addClass("active").siblings("span").removeClass("active");
					flag = true;
					if($(this).text()=="沥青"){
						proportion("02");
						parem.processType='02';
					}else{
						proportion("01");
						parem.processType='01';
					}
					getRoadPileKey();
					initpage();
				});
				getRoadPileKey();
			});
		}
	
	}
});
